from django.shortcuts import render
from django.http import JsonResponse
from system.models import Dept,Menu
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from utils.findButtonPer import findButtonPermission

def dept_page(request):
    # 这里进行判断权限部分
    role_obj = request.user.role.first()
    result = findButtonPermission(role_obj=role_obj,key='dept')
    return render(request, 'system/dept/dept.html',result)

def deptAdd_page(request):
    return render(request, 'system/dept/insert.html')

def deptEdit_page(request):
    return render(request, 'system/dept/edit.html')

# 查询数据构造成树
@login_required()
def getDeptDataTree(request):
    try:
        dept_list = Dept.objects.all()
        list_dept=[]
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询数据失败！'})
    for i in dept_list:
        dict = {}
        dict['id'] = i.id
        # dict['key'] = i.key
        dict['title'] = i.name # 请注意这里的tree_name必须是tree_name,不能自定义成别name,不然tree.js识别不出
        # dict['sort'] = i.sort
        # dict['owner'] = i.owner
        if i.parent_id is not None:
            dict['parent'] = int(i.parent_id)
        else:
            dict['parent'] = None
        # dict['phone'] = i.phone
        # dict['email'] = i.email
        # dict['create_datetime'] = i.create_datetime.strftime("%Y-%m-%d %H:%M:%S")
        # dict['status'] = i.status
        # dict['description'] = i.description
        list_dept.append(dict)
    res = []
    for con in list_dept:
        res.append(con)
    Result = {'code': 0, 'msg': '成功！', 'data': res}
    return JsonResponse(Result)

@login_required()
def getDeptData(request,id):
    try:
        if id==0:
            dept_list = Dept.objects.all()
            counts = Dept.objects.count()
        else:
            dept_list = Dept.objects.filter(parent_id=id)
            counts = Dept.objects.filter(parent_id=id).count()
        list_dept=[]
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询dept数据失败！'})
    for i in dept_list:
        dict = {}
        dict['id'] = i.id
        dict['key'] = i.key
        dict['title'] = i.name
        dict['sort'] = i.sort
        if i.parent_id is not None:
            dict['parent'] = int(i.parent_id)
        else:
            dict['parent'] = None
        dict['owner'] = i.owner
        dict['phone'] = i.phone
        dict['email'] = i.email
        dict['status'] = i.status
        dict['create_datetime'] = i.create_datetime.strftime("%Y-%m-%d %H:%M:%S") 
        dict['description'] = i.description
        list_dept.append(dict)
    res = []
    for contact in list_dept:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！', 'count': counts, 'data': res}
    return JsonResponse(Result)
@login_required()
def addDeptData(request):
    get_key = request.POST.get('key')
    get_name = request.POST.get('name')
    # 这里前端获取下拉框的时候，传上来默认就是名字就叫select
    get_parent = request.POST.get('select')
    get_owner = request.POST.get('owner')
    get_phone = request.POST.get('phone')
    get_email = request.POST.get('email')
    get_description = request.POST.get('description')
    #  这里的先判断是否存在唯一值，为了能够适配所有的数据库版本，这里并不能采用插入数据返回的数据库状态码来判断
    try:
        keys = Dept.objects.values_list('key',flat=True)
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询dept数据失败！'})
    if get_key in keys:
        return JsonResponse({'code': 4001, 'msg': 'key值重复，请修改！'})
    try:
        keys = Dept.objects.create(key=get_key,name=get_name,parent_id=get_parent,owner=get_owner,
        phone=get_phone,email=get_email,description=get_description,creator_id=request.user.id,dept_belong_id=request.user.dept.id)
    except Exception as e:
        return JsonResponse({'code': 4002, 'msg': '创建新的机构失败，请联系管理员！'})
    Result = {'code': 0, 'msg': '创建新的机构成功'}
    return JsonResponse(Result)
@login_required()
def editDeptData(request,id):
    key = request.POST.get('key')
    name = request.POST.get('name')
    parent = request.POST.get('parent_id')
    owner = request.POST.get('owner')
    phone = request.POST.get('phone')
    email = request.POST.get('email')
    sort = request.POST.get('sort')
    status = request.POST.get('status')
    description = request.POST.get('description')
    try:
        Dept.objects.filter(pk=id).update(key=key,name=name,parent_id=parent,owner=owner,phone=phone,email=email,
        sort=sort,status=status,description=description,modifier=request.user.id)
    except Exception as e:
        return JsonResponse({'code': 4001, 'msg': '唯一值出现重复！请检查部门代码。'})
    Result = {'code': 0, 'msg': '修改新的机构成功'}
    return JsonResponse(Result)
@login_required()
def delDeptData(request,id):
    try:
        dept_obj = Dept.objects.get(pk=id)
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '未找到删除对象！'})
    # 这里得判断一下是否存在关联
    dept_count = Dept.objects.filter(parent_id=dept_obj.id).count()
    if dept_count > 0:
        return JsonResponse({'code': 201, 'msg':'该数据存在关联对象，不允许删除！'})
    try:
        dept_obj.delete()
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '删除对象失败！'})
    return JsonResponse({'code': 0, 'msg':'删除成功！'})